import React from 'react'
import Layout from '../core/Layout'
import { Form, Input, Button, Upload, Select, message  } from 'antd'
import { UploadOutlined } from '@ant-design/icons';
import ProductCategories from '../../helper/productCategories'
import { useState } from 'react'
import { API } from '../../config'
import axios from 'axios'
import { isAuth } from '../../helper/auth'


const { Option } = Select;
const {token, user} = isAuth()


export default function AddProduct() {
	const [form] = Form.useForm();
	const categories = ProductCategories()
	const [file, setFile] = useState()
	const props = {
		// 后面统一上传,所以在这里停止默认上传
		// beforeUpload 上传文件之前的钩子，参数为上传的文件，若返回 false 则停止上传
		beforeUpload (file) {
			// 随时改变图片文件
			setFile(file)
			return false
		}
	}
	const onFinish = async value => {
		// 需要提交的格式为 formData 类型
		const formData = new FormData()
		for (let attr in value) {
			formData.append(attr, value[attr])
		}
		formData.append('photo', file)
		const res = await axios.post(`${API}/product/create/${user._id}`, formData, {
			headers: {
				Authorization: `Bearer ${token}`
			}
		})
		if (res.status === 200 ){
			message.success('商品添加成功')
			form.resetFields()

		}
	}
	return (
		<>
			<Layout title="添加商品">
				<Form onFinish={onFinish} initialValues={{ category:'-1' }} form={form}>
					<Form.Item key={Math.random()}>
						<Upload {...props}>
    					<Button icon={<UploadOutlined />}>上传商品封面</Button>
  					</Upload>,
					</Form.Item>
					<Form.Item
        		label="商品名称"
        		name="name"
        		rules={[{ required: true, message: '请输入商品名称!' }]}
      		>
        		<Input />
      		</Form.Item>
					<Form.Item
        		label="商品描述"
        		name="description"
        		rules={[{ required: true, message: '请输入商品描述!' }]}
      		>
        		<Input />
      		</Form.Item>
					<Form.Item
        		label="商品价格"
        		name="price"
        		rules={[{ required: true, message: '请输入商品价格!' }]}
      		>
        		<Input />
      		</Form.Item>
					<Form.Item
        		label="商品分类"
        		name="category"
        		rules={[{ required: true, message: '请输入商品分类!' }]}
      		>
        		<Select>
							<Option value="-1">请选择分类</Option>
							{
								categories.map(item => {
									return <Option value={item._id} key={item._id}>{item.name}</Option>
								})
							}
    				</Select>
      		</Form.Item>
					<Form.Item
        		label="商品数量"
        		name="quantity"
        		rules={[{ required: true, message: '请输入商品数量!' }]}
      		>
        		<Input />
      		</Form.Item>
					<Form.Item
        		label="是否需要运算"
        		name="shipping"
        		rules={[{ required: true, message: '是否需要运算!' }]}
      		>
        		<Select>
							<Option value="1">是</Option>
							<Option value="0">否</Option>
    				</Select>
      		</Form.Item>
					<Form.Item>
        		<Button type="primary" htmlType="submit">
        		  添加商品
        		</Button>
      		</Form.Item>
				</Form>
			</Layout>
		</>
	)
}
